﻿namespace TomatoBreak.Web
{
    using System;
    using System.Linq;
    using System.Web.Mvc;

    public static class ModelStateDictionaryHelper
    {
        public static object Errors(this ModelStateDictionary instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            return instance.Select(ms => new
                                            {
                                                Name = ms.Key,
                                                Messages = ms.Value
                                                           .Errors
                                                           .Select(error => (error.Exception == null) ? error.ErrorMessage : error.Exception.Message)
                                                           .Where(error => !string.IsNullOrWhiteSpace(error))
                                                           .ToList()
                                            })
                           .Where(ms => ms.Messages.Any())
                           .ToList();
        }
    }
}